<template>
  <div>
    <n-upload
      action="/api/upload"
      list-type="image"
      v-model:file-list="fileList"
      show-download-button
      :create-thumbnail-url="createThumbnailUrl"
      @download="handleDownload"
    >
      <n-button>上传文件</n-button>
    </n-upload>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { createDiscreteApi } from "naive-ui";
import { downloadFile } from "../../api/api";

const { message } = createDiscreteApi(["message"]);

function createThumbnailUrl(file) {
  if (!file) return void 0;
  // console.log(file)
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve("https://07akioni.oss-cn-beijing.aliyuncs.com/07akioni.jpeg");
    }, 1e3);
  });
}

function handleDownload(file) {
  // console.log(file.name);
  downloadFile(file.name).then((res) => {
    if (res.status == 200) {
      // 文件下载功能
      const blob = new Blob([res.data])
      const downloadElement = document.createElement('a');
      const href = window.URL.createObjectURL(blob); 
      downloadElement.href = href;
      downloadElement.download = file.name;
      document.body.appendChild(downloadElement);
      downloadElement.click();
      document.body.removeChild(downloadElement); 
      window.URL.revokeObjectURL(href); 
      message.success(`下载成功：${file.name}`);
    }
  });
}

</script>

<style lang="scss" scoped></style>
